package pw.hais.main.main_app.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.squareup.okhttp.Response;

import pw.hais.http.Http;
import pw.hais.http.base.OnHttpListener;
import pw.hais.http.image.CacheManager;
import pw.hais.http.image.LocalCache;
import pw.hais.main.R;
import pw.hais.main.main_app.app.BaseActivity;
import pw.hais.main.main_app.app.V;
import pw.hais.main.main_app.dao.LeanDao;
import pw.hais.main.main_app.model.LeadModel;
import pw.hais.utils.EmptyUtil;
import pw.hais.utils.L;
import pw.hais.utils.SPUtils;

/**
 * Created by hais1992 on 2015/12/14.
 */
public class UserActivity extends BaseActivity implements View.OnClickListener {
    private static final int START_ALBUM_CODE = 222;
    private static final String SELECT_IMAGE_KEY = "http://localhost:/select_photo.jpg";
    private static final int CUTTING_REQUESTCODE = 333;
    private EditText edit_username, edit_email, edit_mobilePhone, edit_createdAt;
    private Button btn_out_login;
    private ImageView image_userphoto;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user);

        edit_username = (EditText) findViewById(R.id.edit_username);
        edit_email = (EditText) findViewById(R.id.edit_email);
        edit_mobilePhone = (EditText) findViewById(R.id.edit_mobilePhone);
        edit_createdAt = (EditText) findViewById(R.id.edit_createdAt);
        btn_out_login = (Button) findViewById(R.id.btn_out_login);
        image_userphoto = (ImageView) findViewById(R.id.image_userphoto);
        btn_out_login.setOnClickListener(this);
        image_userphoto.setOnClickListener(this);


        edit_username.setText(app.user.username);
        edit_email.setText(app.user.email);
        edit_mobilePhone.setText(app.user.mobilePhoneNumber);
        edit_createdAt.setText(app.user.createdAt);
        if (app.user.userPhoto != null) {
            Http.displayImage(image_userphoto, app.user.userPhoto.url);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_user, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_edit) {
            L.showShort("暂不支持修改！");
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_out_login:
                if ("保存修改".equals(btn_out_login.getText())) {
                    updataPhoto();
                } else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(context);
                    builder.setTitle("是否退出");
                    builder.setMessage("是否退出登录？");
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            app.user = null;
                            SPUtils.delObject(V.SP.USER);
                            finish();
                            L.showShort("已退出登录.");
                        }
                    }).setNegativeButton("取消", null);
                    builder.create().show();
                }
                break;
            case R.id.image_userphoto:
                Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*.jpg");
                startActivityForResult(intent, START_ALBUM_CODE);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            switch (requestCode) {
                case START_ALBUM_CODE:
                    //裁剪图片
                    Intent intent = new Intent();
                    // 设置裁剪
                    intent.putExtra("crop", "true");
                    intent.setAction("com.android.camera.action.CROP");
                    intent.putExtra("return-data", true);
                    //设置裁剪图片的比例
                    intent.putExtra("aspectX", 1);
                    intent.putExtra("aspectY", 1);
                    //设置获得裁剪图片的大小
                    intent.putExtra("outputX", 400);
                    intent.putExtra("outputY", 400);
                    intent.setDataAndType(data.getData(), "image/*.jpg");
                    startActivityForResult(intent, CUTTING_REQUESTCODE);
                    break;
                case CUTTING_REQUESTCODE:
                    Bitmap bm = data.getParcelableExtra("data");
                    CacheManager.putBitmapCacheCover(SELECT_IMAGE_KEY, bm);
                    image_userphoto.setImageBitmap(bm);
                    btn_out_login.setText("保存修改");
                    break;

            }

        }
    }

    /**
     * 上传头像
     */
    private String oldUserPhotoObjectId;
    private void updataPhoto() {
        try {
            if(app.user.userPhoto!=null)oldUserPhotoObjectId = app.user.userPhoto.objectId;

            loadDialogShow("正在上传头像..");
            LeanDao.updateUserPhoto(CacheManager.IMAGE_CACHE_DIR, LocalCache.getFileNameByUrl(SELECT_IMAGE_KEY), new OnHttpListener<LeadModel>() {
                @Override
                public void onSuccess(Response response, LeadModel data) {
                    loadDialogDismiss();
                    if (EmptyUtil.emptyOfString(data.error)) {
                        L.showShort("头像修改成功！");
                        if(oldUserPhotoObjectId!=null)LeanDao.deleteFile(oldUserPhotoObjectId, null);
                        btn_out_login.setText("退出登录");
                    } else {
                        L.showShort("修改失败." + data.error);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
